﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Gp.Scripts.Core;
using Gp.Scripts.GUI;
using QFramework;
using UnityEngine;

namespace Gp.Scripts.Core {
    public class AIPlayer : BattlePlayer {
        public bool DebugMode;
        public AITurnCounter TurnCounter { get; private set; }
        public override void Init() {
            TurnCounter = new AITurnCounter();
            TurnCounter.OnInit(this);
        }


        public override IEnumerator ResolveReaction<T>(List<BaseReactionEntity> wrappers, T args) {
            // foreach (var w in wrappers) {
            //     if (w.CanPerform(args)) yield return w.OnTrigger(args);
            // }
            yield break;
        }


        public override IEnumerator ResolveOption(SkillEntity skill, IEnumerable<OptionItem> args) {
            foreach (var item in args) {
                item.OnSelect();
                yield break;
            }
        }
        
        
        
        
        
        public override void Play() {
            var scene = Global.Get<BattleSystem>().BattleSettle;
            scene.AddSequenceBuffer("AI Execute", PlayCoroutine(scene));
        }



        private IEnumerator PlayCoroutine(Core.BattleSettleRoot model) {
            // 选择单位
            var unitsOrdered = UnitOrder(model);

            // var state = Global.Get<BattleSystem>().CurTurnState;
            // foreach (var unit in unitsOrdered) {
            //     var root = unit.EntityConfig.aiBrainPreset.GetAIBrain().RootNode();
            //     if (root == null) break;
            //     root.Init(state, unit);
            //     
            //
            //     yield return root.Execute();
            // }
            //



            while (Global.Get<BattleSystem>().IsBlocked) {
                yield return 0;
            }
            
            
            Global.Get<BattleSystem>().SendEvent(new AITurnEndArgs());
            Global.Get<BattleSystem>().NextTurn();
        }


        private IEnumerable<BaseUnit> UnitOrder(Core.BattleSettleRoot model) {
            var units = model.GetCurrentUnits().Where(BattleLogic.CanUnitPerform).ToList();
            units.Sort((u1, u2) => Random.Range(-1, 1));
            return units;
        }



        /// <summary>
        /// 实现行动计数业务逻辑。当玩家进行行动后，所有敌人的行动计数都会减一。当结果归零时，对方将会开展行动。
        /// </summary>
        /// <returns></returns>
        public IEnumerator ReduceTurnCounter() {
            yield return TurnCounter.ReduceTurnCounter();
        }
    }
    
    
    
    public class AITurnEndArgs { }
}